import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
dotenv.config();

class JWTService {
  // 生成访问令牌
  static generateAccessToken(userId, username) {
    const payload = {
      userId,
      username,
      type: 'access',
      iat: Math.floor(Date.now() / 1000),
      exp: Math.floor(Date.now() / 1000) + (parseInt(process.env.JWT_EXPIRES_IN) || 3600), // 默认1小时
      // 增加额外信息
      device: 'unknown', // 将在后续从请求中提取
      ip: 'unknown',     // 将在后续从请求中提取
      clientId: 'web'    // 客户端标识
    };
    
    return jwt.sign(payload, process.env.JWT_SECRET);
  }
  
  // 生成刷新令牌
  static generateRefreshToken(userId, username) {
    const payload = {
      userId,
      username,
      type: 'refresh',
      iat: Math.floor(Date.now() / 1000),
      exp: Math.floor(Date.now() / 1000) + 7 * 24 * 3600, // 7天
      tokenId: Math.random().toString(36).substr(2, 9) // 唯一tokenId
    };
    
    return jwt.sign(payload, process.env.JWT_REFRESH_SECRET || process.env.JWT_SECRET);
  }
  
  // 验证令牌
  static verifyToken(token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      return { isValid: true, decoded };
    } catch (error) {
      return { 
        isValid: false, 
        error: error.name === 'TokenExpiredError' ? '令牌已过期' : '无效的令牌' 
      };
    }
  }
  
  // 验证刷新令牌
  static verifyRefreshToken(token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_REFRESH_SECRET || process.env.JWT_SECRET);
      
      // 验证令牌类型
      if (decoded.type !== 'refresh') {
        return { isValid: false, error: '无效的刷新令牌类型' };
      }
      
      return { isValid: true, decoded };
    } catch (error) {
      return { 
        isValid: false, 
        error: error.name === 'TokenExpiredError' ? '刷新令牌已过期' : '无效的刷新令牌' 
      };
    }
  }
  
  // 从令牌中提取用户信息
  static extractUserInfo(token) {
    try {
      const decoded = jwt.decode(token);
      if (!decoded) {
        return null;
      }
      
      return {
        userId: decoded.userId,
        username: decoded.username
      };
    } catch (error) {
      return null;
    }
  }
  
  // 增加设备和IP信息到令牌负载
  static enhanceAccessTokenWithRequestInfo(token, req) {
    try {
      const decoded = jwt.decode(token);
      
      // 添加设备和IP信息
      decoded.device = req.headers['user-agent'] || 'unknown';
      decoded.ip = req.ip || req.connection.remoteAddress || 'unknown';
      
      // 重新签名令牌
      return jwt.sign(decoded, process.env.JWT_SECRET, {
        expiresIn: decoded.exp - decoded.iat
      });
    } catch (error) {
      console.error('增强令牌失败:', error);
      return token; // 如果失败，返回原令牌
    }
  }
}

export default JWTService;